package be.myandroid.games.menu;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import be.myandroid.games.Configuration;
import be.myandroid.games.spritetext.LabelMaker;
import be.myandroid.games.spritetext.Projector;

public class GameMenuItem {
	private int id;
	private States state = States.CREATED;
	public String text;
	public float x;// -1 ... 1
	public float y;// -1 ... 1
	private float width;
	private float height;
	public boolean visible = true;
	public boolean enable = true;
	public boolean isLayedOut = false;
    private float[] mScratch = new float[8];
    private float[] MAX = Configuration.getInstance().MAX_SCREEN_SIZE;
	
	private enum States {CREATED,INITIALIZED};
	
	public int getId() {
		if(state == States.INITIALIZED)
			return id;
		(new Exception("Cannot access id before initialization")).printStackTrace();
		return -1;
	}
	
	public GameMenuItem(String text){
		this.text = text;
	}
	
	public void OnClick(float xPos, float yPos) {
		if(!isLayedOut)
			(new Exception("MenuItem is not layedout yet")).printStackTrace();
		
		if(Math.abs(xPos - x) * 2.0f < width)
		{
			if(enable && Math.abs(yPos - y) * 2.0f < height)
				OnClick();
		}
	}
	
	public void OnClick(){
		
	}
	
	public void draw(GL10 gl, LabelMaker parent, Projector projector){
		if(!visible)
			return;
		if(!isLayedOut)
			(new Exception("Layout MenuItem before drawing")).printStackTrace();
		
        mScratch[0] = x * MAX[0];
        mScratch[1] = y * MAX[1];
        mScratch[2] = 0.0f;
        mScratch[3] = 1.0f;
        projector.project(mScratch, 0, mScratch, 4);
        float sx = mScratch[4];
        float sy = mScratch[5];
        float height = parent.getHeight(getId());
        float width = parent.getWidth(getId());
        float tx = sx - width * 0.5f;
        float ty = sy - height * 0.5f;
        parent.draw(gl, tx, ty, getId());
	}
	
	public void initialize(GL10 gl, LabelMaker maker, Paint paint){
		initialize(gl, null, maker, paint);
	}
	
	public void initialize(GL10 gl, Drawable background, LabelMaker maker, Paint paint){
		id = maker.add(gl, background, text, paint, 0, 0);
		width = maker.getWidth(id) * 2.0f;// / mWidth;
		height = maker.getHeight(id) * 2.0f;// / mHeight;
		state = States.INITIALIZED;
	}
	
	public void layout(float mWidth, float mHeight){
		if(isLayedOut)
			return;
		
		isLayedOut = true;
		width = width /mWidth;
		height = height / mHeight;
	}
	
	public float getHeight() {
		return height;
	}
	public float getWidth() {
		return width;
	}
}